package app;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.rygh.core.algorithm.OrderedPrecisionRecall;
import org.rygh.core.html.table.HtmlTable;
import org.rygh.core.html.table.TableData;
import org.rygh.core.html.table.TableTuple;
import org.rygh.core.model.common.MapList;
import org.rygh.core.model.tree.Branch;
import org.rygh.core.util.UIo;
import org.rygh.core.util.counter.CounterTuple;
import org.rygh.core.util.counter.SimpleCounter;
import org.rygh.core.xml.UXml;
import org.rygh.gui.swing.USwing;
import org.rygh.semantic.gui.swing.input.Input;
import org.rygh.semantic.jena.SDatabase;
import org.rygh.semantic.model.ex.FactSet;
import org.rygh.semantic.model.rdf.Entity;
import org.rygh.semantic.model.rdf.Fact;
import org.rygh.semantic.model.rdf.Predicate;
import org.rygh.semantic.model.rdf.Prefix;
import org.rygh.semantic.sparql.ResultList;
import org.rygh.semantic.sparql.SparQL;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import wsi.dataguide.DataGuide;
import wsi.dataguide.DataGuideLoader;
import wsi.dataguide.XmlTableDocument;
import wsi.dataguide.XmlTableNode;
import wsi.dataguide.tree.WSXmlLeaf;
import wsi.dataguide.tree.WSXmlParser;
import wsi.dataguide.tree.WSXmlTree;
import wsi.depend.DependencyDetector;
import wsi.detect.Caller.CallResult;
import wsi.function.DirManager;
import wsi.function.Function;
import wsi.function.FunctionController;
import wsi.function.oauth.MyApi;
import wsi.function.oauth.OAuthController;
import wsi.function.oauth.RdioApi;
import wsi.match.SubtreeController;
import wsi.script.AppConfig;
import wsi.subgraph.ExtractWorker;
import wsi.subgraph.tree.EntityLeaf;
import wsi.subgraph.tree.EntityObject;
import wsi.subgraph.tree.EntityTree;
import wsi.subgraph.tree.EntityTreeLoader;

public class test {

	static void extractInputFiles(File dest) {
		if (!dest.exists())
			dest.mkdir();

		File dir = AppConfig.shared().getFunctionsFolder();

		String FNAME = "candidate_inputs.xml";

		for (File ws : dir.listFiles()) {
			if (!ws.isDirectory())
				continue;

			File nws = new File(dest, ws.getName());
			nws.mkdir();

			for (File f : ws.listFiles()) {
				if (!f.isDirectory())
					continue;

				File inf = new File(f, FNAME);
				if (!inf.exists())
					continue;

				File nf = new File(nws, f.getName());
				nf.mkdir();

				UIo.copy(inf, new File(nf, FNAME));

			}
		}
	}

	public static void main(String... args) {
		AppConfig.init();

		String content = UIo.readFile(new File(
				"/home/nanmus/Downloads/publishers.xml"));

		Input input = new Input(new Entity("y:Scholastic_Corporation"), null,
				"Scholastic Corporation");
		WSXmlParser parser = new WSXmlParser(input, content, true);
		WSXmlTree tree = parser.parse();

		UIo.saveFile(new File("/home/nanmus/Downloads/publishers_out.xml"),
				tree.toXmlString());
	}

	static void oauth() throws Exception {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

		OAuthService service = new ServiceBuilder().provider(MyApi.class)
				.apiKey("InuGshEWxjURnsrrZhqp")
				.apiSecret("VidBVVHBoAYXDTLoOrmyJKdZhuAyuhpj").build();

		Token requestToken = service.getRequestToken();
		String authUrl = service.getAuthorizationUrl(requestToken);

		System.out.println(authUrl);

		USwing.browse(authUrl);

		String str = JOptionPane
				.showInputDialog("Please input the authentication code.");

		Verifier v = new Verifier(str);

		Token accessToken = service.getAccessToken(requestToken, v);
		OAuthRequest request = new OAuthRequest(Verb.GET,
				"http://api.discogs.com/database/search?type=artist&q=Amitabh_Bachchan");
		service.signRequest(accessToken, request);

		Response response = request.send();
		System.out.println(response.getCode());
		System.out.println(response.getBody());
	}

	static void oauth2() throws Exception {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

		OAuthController ctrl = new OAuthController(RdioApi.class.getName());

		if (!ctrl.connect(null))
			return;

		String url = "http://api.rdio.com/1/";

		CallResult resp = ctrl.post(url, "method", "search", "format", "xml",
				"types", "Artist", "query", "Mary Martin");
		// String resp = ctrl.get(url);

		UIo.saveFile(new File("E:/a.xml"), resp.content);
	}

	static void regex01() {
		String s = "amr'd_dfe)83?.fd().FESl";

		System.out.println(s.replaceAll("[^a-zA-Z0-9_()]", ""));
	}

	static void rename(File dir, String prefix) {
		for (File f : dir.listFiles()) {
			if (f.isDirectory()) {
				rename(f, prefix);
			} else {
				String name = f.getName();
				int pos = name.indexOf("_13");

				File nf = new File(f.getParent(), prefix + name.substring(pos));

				if (!nf.exists()) {
					f.renameTo(nf);
					System.out.println(nf.getAbsolutePath());
				}
			}
		}

	}

	static void tdbCount() {

		SparQL query = new SparQL();

		Fact fact = new Fact(new Entity("?s"), new Predicate("y:hasGender"),
				new Entity("?o"));

		query.addFact(fact);
		// query.countAll();
		// query.countDistinct("?x", "?o");
		query.distinct("?o");

		ResultList res = SDatabase.shared().select(query);

		System.out.println(res);
	}

	static void testAP() {
		OrderedPrecisionRecall p = new OrderedPrecisionRecall(6);

		p.retrieve(true);
		p.retrieve(false);
		p.retrieve(false);
		p.retrieve(true);
		p.retrieve(true);
		p.retrieve(true);

		System.out.println(p.getAveragePrecision());

	}

	static void testDepend() {
		AppConfig.init();

		Function provider = null, dependant = null;

		String providerName;
		String dependantName;

		providerName = "getArtistInfoByName";
		// providerName = "getReleasesByArtistId";
		dependantName = "getReleasesByArtistId";

		for (Function f : FunctionController.shared().getFunctions(
				"music_brainz")) {
			System.out.println("processing " + f.getName());

			if (f.getName().equals(providerName))
				provider = f;

			if (f.getName().equals(dependantName))
				dependant = f;

		}

		System.out.println("begin");

		assert dependant != null;

		DependencyDetector d = new DependencyDetector(dependant);
		d.setProvider(provider);

		if (d.detect())
			System.out.println("detected " + d.getDependency().getXpath());

	}

	static void testEntityTreeLoader() {
		String path = "E:/Projects/Data/Auto/runs/whole_110_inputs_1002_server/functions/music_brainz/getArtistInfoByName/data/yagohop_yA._R._Rahman_1_0.100.txt";
		String content = UIo.readFile(new File(path));

		FactSet fs = new FactSet();
		fs.loadJson(content);

		Entity entity = new Entity("y:A._R._Rahman");
		EntityTreeLoader loader = new EntityTreeLoader(entity, fs);
		EntityTree tree = loader.load();
		System.out.println(tree.toString());
	}

	static void testEvaluateXPath() throws Exception {
		String file = "E:/Data/Dropbox/Shared/ClementThesis/WS-DATA/functions/music_brainz/getArtistInfoByName/xmls/Amitabh_Bachchan.xml";

		DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
		Document doc = bf.newDocumentBuilder().parse(file);

		XPath xpath = XPathFactory.newInstance().newXPath();

		String exp;
		NodeList n;
		// Node name = null;

		/**/

		exp = "/metadata/artist-list[1]/artist[name=\"Amitabh Bachchan\"]/@id";
		n = (NodeList) xpath.evaluate(exp, doc, XPathConstants.NODESET);

		for (int i = 0; i < n.getLength(); i++) {
			System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
					n.item(i).getTextContent());

			// name = n.item(0);
		}

		// /**/
		//
		// exp = "/metadata/artist-list[1]/artist[7]/@type";
		// n = (NodeList) xpath.evaluate(exp, doc, XPathConstants.NODESET);
		//
		// for (int i = 0; i < n.getLength(); i++) {
		// System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
		// n.item(i).getTextContent());
		//
		// name = n.item(0);
		// }
		//
		// /**/
		//
		// exp = "/metadata/artist-list/artist[3]/name";
		// n = (NodeList) xpath.evaluate(exp, doc, XPathConstants.NODESET);
		//
		// for (int i = 0; i < n.getLength(); i++) {
		// System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
		// n.item(i).getTextContent());
		//
		// name = n.item(0);
		// }
		//
		// exp = "..";
		// n = (NodeList) xpath.evaluate(exp, name, XPathConstants.NODESET);
		//
		// Node parent = null;
		//
		// for (int i = 0; i < n.getLength(); i++) {
		// System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
		// n.item(i).getTextContent());
		//
		// parent = n.item(0);
		// assert parent != null;
		// }
		//
		// exp = "../life-span/begin";
		// n = (NodeList) xpath.evaluate(exp, name, XPathConstants.NODESET);
		//
		// Node begin = null;
		//
		// for (int i = 0; i < n.getLength(); i++) {
		// System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
		// n.item(i).getTextContent());
		//
		// begin = n.item(0);
		// assert begin != null;
		// }
		//
		// /**/
		//
		// exp =
		// "/metadata/artist-list/artist[@id=\"54d0baf3-1511-4c91-8042-becf6573807e\"]/name";
		//
		// n = (NodeList) xpath.evaluate(exp, doc, XPathConstants.NODESET);
		// name = null;
		//
		// for (int i = 0; i < n.getLength(); i++) {
		// System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
		// n.item(i).getTextContent());
		//
		// name = n.item(0);
		// }
		//
		// exp = "..";
		// n = (NodeList) xpath.evaluate(exp, name, XPathConstants.NODESET);
		//
		// parent = null;
		//
		// for (int i = 0; i < n.getLength(); i++) {
		// System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
		// n.item(i).getTextContent());
		//
		// parent = n.item(0);
		// }
		//
		// exp = "../life-span/begin";
		// n = (NodeList) xpath.evaluate(exp, name, XPathConstants.NODESET);
		//
		// begin = null;
		//
		// for (int i = 0; i < n.getLength(); i++) {
		// System.out.printf("RES:[%s,%s]\n", n.item(i).getNodeName(),
		// n.item(i).getTextContent());
		//
		// begin = n.item(0);
		// }
	}

	static void testFreq() {
		SimpleCounter<Integer> c = new SimpleCounter<>();

		c.set(1, 1);
		c.set(2, 2);
		c.set(3, 3);
		c.set(4, 4);
		c.set(5, 5);
		c.set(6, 6);
		c.set(7, 7);
		c.set(8, 8);
		c.set(9, 9);
		c.set(10, 10);

		List<CounterTuple<Integer>> list = c.getListInRange(.02, .1);

		for (CounterTuple<Integer> i : list)
			System.out.println(i.getKey());

	}

	static void testHtmlTable() {
		String[][] values = {
		/**/{ "H1", "H2", "H3" },
		/**/{ "a", "b1", "c1" },
		/**/{ "a", "b1", "c2" },
		/**/{ "a", "b1", "c3" },
		/**/{ "a", "b2", "c4" },
		/**/{ "a", "b2", "c1" },
		/**/{ "b", "b1", "c2" },
		/**/{ "b", "b2", "c4" },
		/**/{ "b", "b2", "c3" }, };

		TableData valueList = new TableData();

		for (String[] i : values) {
			TableTuple tuple = new TableTuple();

			for (String j : i)
				tuple.add(j);

			valueList.add(tuple);
		}

		HtmlTable table = new HtmlTable("Caption", valueList, false);

		System.out.println(table.toString());
		UIo.saveFile(new File("e:/a.html"), table.toString());

	}

	@SuppressWarnings({ "null", "deprecation" })
	static void testTreeCoverage() {
		String path = "E:/Data/Dropbox/Shared/ClementThesis/WS-DATA/functions/music_brainz/getArtistInfoByName/";

		String name = "y:Amitabh_Bachchan";
		String dgfile = path + "dataguides.xml";
		String xmlfile = path + "xmls/" + name + ".xml";

		DataGuideLoader dgloader = new DataGuideLoader(UIo.readFile(new File(
				dgfile)));
		DataGuide dataGuide = dgloader.load();

		// System.out.println(dataGuide);

		WSXmlParser parser = new WSXmlParser(new Input(name),
				UIo.readFile(new File(xmlfile)), true);
		WSXmlTree tree = parser.parse();

		// System.out.println(tree);

		WSXmlLeaf left, right;

		left = dataGuide.getConcreteRoot();
		right = tree.getConcreteRoot();

		System.out.printf("left %s\nright %s\n\n", left, right);

		MapList<WSXmlLeaf, WSXmlLeaf> leftMap = new MapList<>();
		MapList<WSXmlLeaf, WSXmlLeaf> rightMap = new MapList<>();
		SubtreeController ctrl = null;// new SubtreeController();

		left.contains(right, null, ctrl, leftMap, rightMap);

		List<WSXmlLeaf> subroots = null;

		// System.out.printf("Subroots %d\n", subroots.size());

		for (WSXmlLeaf r : subroots)
			System.out.printf("\t%s\n", r);

		System.out.printf("Left %d\n", leftMap.size());

		for (Entry<WSXmlLeaf, List<WSXmlLeaf>> i : leftMap.entrySet()) {
			System.out.println("Key " + i.getKey());

			for (WSXmlLeaf j : i.getValue())
				System.out.println("\t " + j);
		}

		System.out.printf("Right %d\n", rightMap.size());

		for (Entry<WSXmlLeaf, List<WSXmlLeaf>> i : rightMap.entrySet()) {
			System.out.println("Key " + i.getKey());

			for (WSXmlLeaf j : i.getValue())
				System.out.println("\t " + j);
		}

	}

	static void testTreeLink() {
		AppConfig.init();

		Function function = FunctionController.shared().getFunction(
				"music_brainz", "getArtistInfoByName");

		DirManager dir = new DirManager(function);
		FactSet facts;

		String fname = "Amitabh_Bachchan";

		ExtractWorker yh = new ExtractWorker(dir, null);
		facts = yh.load(fname);

		Entity entity = new Entity("y:" + fname);
		EntityTreeLoader loader = new EntityTreeLoader(entity, facts);
		EntityTree tree = loader.load();

		EntityLeaf root = tree.getConcreteRoot();
		EntityLeaf left, right;

		left = root.getChildren().get(0).getChildren().get(0);
		left = root;
		right = root.getChildren().get(1).getChildren().get(0);

		Branch<EntityObject, EntityLeaf> branch = tree.link(left, right);

		System.out.println(branch);

	}

	static void testWebHelper() throws Exception {

		String url = "http://www.musicbrainz.org/ws/2/artist/?query=artist:enya";

		String res = UIo.readUrl(url);

		System.out.println(res);
	}

	static void testXmlTable() {
		String[][] values = {
		/**/{ "H1", "H2", "H3" },
		/**/{ "a", "b1", "c1" },
		/**/{ "a", "b1", "c2" },
		/**/{ "a", "b1", "c3" },
		/**/{ "a", "b2", "c4" },
		/**/{ "a", "b2", "c1" },
		/**/{ "b", "b1", "c2" },
		/**/{ "b", "b2", "c2" },
		/**/{ "b", "b2", "c3" }, };

		TableData valueList = new TableData();

		for (String[] i : values) {
			TableTuple tuple = new TableTuple();

			for (String j : i)
				tuple.add(j);

			valueList.add(tuple);
		}

		XmlTableDocument doc = new XmlTableDocument();

		for (Entry<String, String> e : Prefix.DEFAULT_PREFIX.getMap()
				.entrySet())
			doc.addPrefix(e.getKey(), e.getValue());

		XmlTableNode node = new XmlTableNode("test", valueList);
		node.convert();

		doc.addNode(node);

		System.out.println(doc.toString());
		// UIo.saveFile("e:/a.xml", doc.toString());

	}

	static void testXpathReletaiveTo() {

		Pattern p = Pattern.compile("/([^/\\[]+)\\[");
		Matcher m = p
				.matcher("/dataguide/metadata[1]/artist-list[1]/artist[1]/ipi-list[1]/ipi[1]");

		List<String> list = new ArrayList<>();

		boolean tag = false;
		while (m.find()) {
			String s = m.group(1);
			System.out.println(s);

			if (tag) {
				list.add(s);
			}

			if (!tag)
				tag = s.equals("artist");
		}

		System.out.println(list);

	}

	static void toLaTeXString() {

		String content = UIo.readFile(new File("e:/a.txt"));

		String[] lines = content.split("\n");
		String ws = null;

		SimpleCounter<String> counter = new SimpleCounter<>();

		for (String line : lines) {
			String[] vals = line.split("\\s+");

			counter.count(vals[0]);
		}

		for (String line : lines) {
			String[] vals = line.split("\\s+");

			StringBuilder sb = new StringBuilder();

			if (!vals[0].equals(ws)) {
				String s = vals[0];

				sb.append("\\hline\r\n");
				sb.append(String.format("\\multirow{%d}{*}{%s}",
						counter.get(s), s.replaceAll("_", "")));
			}

			ws = vals[0];
			sb.append(" & ");
			sb.append(vals[1].replaceAll("Info", ""));

			for (int i = 12; i < 22; i++) {
				double d = Double.parseDouble(vals[i]);

				sb.append(" & ");
				sb.append(String.format("%.0f", d));
			}

			sb.append(" \\\\ ");

			System.out.println(sb.toString());
		}

	}

	static void transformXsl() {
		String path = "E:/Data/Dropbox/Shared/ClementThesis/WS-DATA/functions/music_brainz/getArtistInfoByName/";
		String xml, xsl;

		xml = UIo.readFile(new File(path + "xmls/Nicole_Kidman.xml"));
		xsl = UIo.readFile(new File(path + "getArtistInfoByName.xsl"));

		System.out.println(UXml.transformXslt(xsl, xml));
	}
}
